package com.ndhutu.ee.util.pay.fuyilai;

import com.alibaba.fastjson.JSONObject;
import com.ndhutu.ee.util.MD5Util;
import com.ndhutu.ee.util.http.OKHttpUtil;
import com.ndhutu.ee.util.pay.Notify;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class FYLPayUtil {
    private static Logger log = LoggerFactory.getLogger(FYLPayUtil.class);

    /**
     * 下单
     * @param config
     * @param payWay    支付方式，0-微信  1-支付宝
     * @param orderNumber
     * @param amount
     * @param body
     * @return
     * @throws Exception
     */
    public static String order(FYLPayConfig config, Integer payWay, String orderNumber, Integer amount, String body) throws Exception{
        Map<String, String> param = new HashMap<>();

        param.put("appid", config.getAppid());
        param.put("body", body);
        param.put("gooddes", body);
        param.put("goodname", body);
        param.put("ip", "127.0.0.1");
        param.put("notify_url", config.getNotifyUrl());
        param.put("out_trade_no", orderNumber);
        param.put("return_url", config.getReturnUrl());
        param.put("total_fee", amount+"");

        String stringSignTemp = OKHttpUtil.sortParam(param, false) + "&key="+config.getKey();
        String sign = MD5Util.encode32(stringSignTemp).toUpperCase();
        param.put("sign", sign);

        String url = null;
        if(payWay == 0){
            url = "http://api.fuyilai.com/version1.0/wx";
        }else if(payWay == 1){
            url = "http://api.fuyilai.com/version1.0/zfb_h5";
        }

        String result = OKHttpUtil.post(url, param);
        log.info("付易来支付下单返回结果："+result);

        return result;
    }

    /**
     * 获取回调请求参数
     * @param request
     * @return
     * @throws Exception
     */
    public static Map<String, String> getNotifyRequestParams(HttpServletRequest request) throws Exception{
        Map<String,String> params = new HashMap<String, String>();

        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        log.info("付易来支付回调参数："+ JSONObject.toJSONString(params));

        return params;
    }

    /**
     * 校验回调请求
     * @param params    回调请求参数
     * @param config
     * @param notify
     * @return
     * @throws Exception
     */
    public static String verifyNotifyRequest(Map<String, String> params, FYLPayConfig config, Notify notify) throws Exception{
        //签名验证
        boolean flag = false;
        String orgSign = params.get("sign");
        params.remove("sign");
        String stringSignTemp = OKHttpUtil.sortParam(params, false) + "&key="+config.getKey();
        String sign = MD5Util.encode32(stringSignTemp).toUpperCase();
        if(sign.equals(orgSign)){
            flag = true;
        }

        if(flag){
            if("ok".equals(params.get("trade_status"))) {
                String orderNumber = params.get("out_trade_no");
                Integer amount = Integer.parseInt(params.get("total_fee"));

                //统一回调
                notify.handleNotify(orderNumber, amount);
                log.info("订单" + orderNumber + "付易来支付回调成功");
            }
            return "ok";
        }else{
            return "failure";
        }
    }

    public static void main(String[] args) throws Exception{
        FYLPayConfig config = new FYLPayConfig() {
            @Override
            public String getAppid() {
                return "0000000231";
            }

            @Override
            public String getNotifyUrl() {
                return "http://test.mm.api.ppmkf.com/mm-api/wallet/fylPayNotify";
            }

            @Override
            public String getReturnUrl() {
                return "http://share.mm.ppmkf.com/pay/success_pay.html";
            }

            @Override
            public String getKey() {
                return "fksmf4tsbddc5ojwnxn9xabazzvuqjv4";
            }
        };

        String result = order(config, 0, "12345", 10, "测试商品");
        System.out.println(result);
    }
}
